<template>
    <div class="app-container">
        <el-row :gutter="10">
            <el-col v-if="isShowLeftPatientInfo" :span="8">
                <nurse-patient-bed-list ref="nursePatientBedListRef"
                                        @patient-selection-change="patientSelectionChange"/>
            </el-col>
            <el-col :span="isShowLeftPatientInfo ? 16:24">
                <div class="search-container">
                    <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
                        <el-form-item label="长/临:" prop="repeatIncaditor">
                            <el-radio-group v-model="queryParams.repeatIncaditor" @change="orderListSelect">
                                <template v-for="(tag, index) in dictDataMap['order_type']">
                                    <el-radio-button :label="tag.dictLabel" :value="tag.dictValue"/>
                                </template>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="下达时间:" prop="admissionTime">
                            <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                                            range-separator="截止" start-placeholder="开始日期" type="daterange"
                                            @change="admissionTimeChange"></el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <query-form-button @handleQuery="orderListSelect" @resetQuery="resetQuery"/>
                            <el-button type="success" @click="orderLabelPrint">
                                <template #icon>
                                    <i-ep-printer/>
                                </template>
                                打印
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <el-table v-adaptive="350" :border="true" :data="orderList" :header-cell-style="$headerCellStyle"
                          :stripe="true" highlight-current-row @select-all="selectAll">
                    <el-table-column :align="'center'" type="selection" width="40">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.checkOk"
                                         :disabled="!(scope.row.groupNumberStyle === '┌' || scope.row.groupNumberStyle === '')"
                                         @change="checkboxChange($event, scope.row)"/>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true"
                                     label="医嘱内容"
                                     prop="orderText">
                        <template #default="scope">
                            <span
                                style="color: #000000;font-size: large;">{{
                                    scope.row.groupNumberStyle != '' ? scope.row.groupNumberStyle : '&nbsp;&nbsp;&nbsp;'
                                }}</span>
                            <span style="margin-left: 5px">{{ scope.row.orderText }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="长/临" prop="repeatIncaditor" width="60">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['order_type']"
                                           :value="scope.row.repeatIncaditor"/>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="是否计价" prop="billingAttr" width="90">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['billing_attr']"
                                           :value="scope.row.billingAttr"/>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="药品规格" prop="packageSpec" width="130"/>
                    <el-table-column :align="'center'" label="途径" prop="channelName" width="120"/>
                    <el-table-column :align="'center'" label="频次" prop="performFreqName" width="110"/>
                    <el-table-column :align="'center'" label="单次用量" prop="numSingle" width="100">
                        <template #default="scope">
                    <span style="margin-left: -15px"> {{ parseFloat(scope.row.numSingle).toFixed(2) }}<dict-data-tag
                        :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                        style="margin: -23px -20px 0px 35px"/></span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="单次剂量" prop="singleDosage" width="120">
                        <template #default="scope">
                    <span style="margin-left: -15px"> {{ parseFloat(scope.row.singleDosage).toFixed(2) }}<dict-data-tag
                        :options="dictDataMap['dose_unit']" :value="scope.row.doseUnits"
                        style="margin: -23px -20px 0px 35px"/></span>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="120">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['sys_drop_speed']"
                                           :value="scope.row.dripSpeed"/>
                        </template>
                    </el-table-column>
                    <el-table-column :align="'center'" label="医嘱说明" prop="remarks" width="120">
                        <template #default="scope">
                            {{ scope.row.remarks }}
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>

<script lang="ts" setup>

import {findOrdersBottleLabel} from "@/api/orders/orders.ts"
import {useDictStoreHook} from "@/store/modules/dict.ts";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('billing_attr', 'order_type', 'spec_unit', 'sys_drop_speed', 'dose_unit'))

const queryParams = ref<any>({
    repeatIncaditor: '0',
    visitIdArray: [],
    classifyValue: '3'
})
const {proxy} = getCurrentInstance() as any;
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([null, null]);
// orders id 集合
const ids = ref<any>([])
const orderList = ref<any>([])
const nursePatientBedListRef = ref()
const objectUrl = ref("")
const isShowLeftPatientInfo = ref<boolean>(true)

function admissionTimeChange(e) {
    if (e) {
        dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
    }
    orderListSelect()
}

// function repeatIncaditorChange () {
//     orderList.value.forEach((order: any) => {
//         order.checkOk = false
//     })
//     orderListSelect()
// }

function handleQuery() {
    nextTick(() => {
        nursePatientBedListRef.value.handleQuery()
    })
}

/**
 * 瓶签明细全选事件 全选/反选
 */
function selectAll() {
    if (ids.value.length === orderList.value.length) {
        orderList.value.forEach((order: any) => {
            order.checkOk = false
        })
        ids.value = []
    } else {
        orderList.value.forEach((order: any) => {
            order.checkOk = true
        })
        ids.value = orderList.value.map((item: any) => item.detailId);
    }
}

// 行选中 默认按照组号相同的勾选或者取消勾选
function checkboxChange(e: boolean, detail: any) {
    if (e) {
        orderList.value.forEach((order: any) => {
            if (detail.groupNumber != null && order.groupNumber === detail.groupNumber && order.visitId == detail.visitId) {
                order.checkOk = true
            }
        })
    } else {
        orderList.value.forEach((order: any) => {
            if (detail.groupNumber != null && order.groupNumber === detail.groupNumber && order.visitId == detail.visitId) {
                order.checkOk = false
            }
        })
    }

}


/**
 * 患者床位列表勾选事件
 */
function patientSelectionChange(visitIds: any) {
    queryParams.value.visitIdArray = visitIds
    orderListSelect()
}

/**
 * 查询瓶签orders 列表
 */
function orderListSelect() {
    if (queryParams.value.visitIdArray.length <= 0) {
        orderList.value = []
        return ElMessage.error("请勾选左侧患者信息后，再操作")
    }
    findOrdersBottleLabel(proxy.$addDateRange(queryParams.value, dateRange.value)).then((res: resType) => {
        orderList.value = res.data
        ids.value = orderList.value
        selectAll()
    })
}

function resetQuery() {
    queryParams.value.repeatIncaditor = ''
    orderListSelect()
}

/**
 * 医嘱瓶签打印
 */
function orderLabelPrint() {
    const checkList = orderList.value.filter((item: any) => item.checkOk)
    if (checkList.length <= 0) {
        return ElMessage.error("请勾选需要打印的药品")
    }
    let submitList: any = []
    checkList.forEach((item: any) => {
        const info = {
            id: item.id,
            groupNumber: item.groupNumber,
            visitId: item.visitId,
            orgId: item.orgId
        }
        submitList.push(info)
    })
    let url = "/business/orders/orderLabelPrint";
    const formData = new FormData()
    formData.append("ordersListStr", JSON.stringify(submitList))
    formData.append("orgId", submitList[0].orgId)
    formData.append("templateCode", "ordersLabel")
    // pdf打印 、打印预览
    proxy.$printPdfPublic(url, formData).then(res => {
        if (res) {
            objectUrl.value = URL.createObjectURL(res)
        } else {
            console.error('打印失败')
        }
    })
}

/**
 * 从个人床位卡点击跳转事件
 * @param isShowLeftPatientInfoThis
 * @param visitId
 */
function initVisitOrderLabel(isShowLeftPatientInfoThis: boolean, visitId: string) {
    isShowLeftPatientInfo.value = isShowLeftPatientInfoThis
    queryParams.value.visitIdArray.push(visitId)
    orderListSelect()
}

function empty() {
    isShowLeftPatientInfo.value = true
    queryParams.value.visitIdArray = []
}

defineExpose({
    handleQuery,
    initVisitOrderLabel,
    empty
})
</script>


<style scoped>

:deep(.el-checkbox.el-checkbox--large .el-checkbox__inner) {
}

</style>
